package user

import (
	"context"
	"github.com/Masterminds/squirrel"
	"ns/pkg/xsql"
	"ns/pkg/xtypes"

	"ns/app/applet/api/internal/svc"
	"ns/app/applet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryUserLogic {
	return &QueryUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryUserLogic) QueryUser(req *types.QueryUserRequest) (resp *types.QueryUserResponse, err error) {
	whereBuilder := l.svcCtx.UserModel.RowBuilder()
	whereBuilder = whereBuilder.OrderBy("created_at DESC, id DESC")

	countBuilder := l.svcCtx.UserModel.CountBuilder("id")

	whereBuilder = whereBuilder.Where("status != ?", 3)
	countBuilder = countBuilder.Where("status != ?", 3)

	// 姓名
	if req.Name != "" {
		whereBuilder = whereBuilder.Where(squirrel.Like{
			"name ": "%" + req.Name + "%",
		})
		countBuilder = countBuilder.Where(squirrel.Like{
			"name ": "%" + req.Name + "%",
		})
	}

	// 手机号
	if req.Mobile != "" {
		whereBuilder = whereBuilder.Where(squirrel.Eq{
			"mobile ": req.Mobile,
		})
		countBuilder = countBuilder.Where(squirrel.Eq{
			"mobile ": req.Mobile,
		})
	}
	// 区域sql拼接
	areaCode := xtypes.AreaCode{
		Province: req.Province,
		City:     req.City,
		Area:     req.Area,
	}
	whereBuilder = xsql.GenSQLByAreaLevel(areaCode, whereBuilder)
	countBuilder = xsql.GenSQLByAreaLevel(areaCode, countBuilder)
	// 类型
	if req.Type != "" {
		whereBuilder = whereBuilder.Where(squirrel.Eq{
			"type ": req.Type,
		})
		countBuilder = countBuilder.Where(squirrel.Eq{
			"type ": req.Type,
		})
	}

	// 先查询总数
	count, err := l.svcCtx.UserModel.FindCount(l.ctx, countBuilder)
	if err != nil {
		return nil, err
	}

	all, err := l.svcCtx.UserModel.FindList(l.ctx, whereBuilder, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}
	list := make([]*types.UserDetail, 0, len(all))
	for _, user := range all {
		list = append(list, &types.UserDetail{
			Id:       user.Id,
			Name:     user.Name,
			Mobile:   user.Mobile,
			Email:    user.Email,
			Level:    int32(user.Level),
			Province: user.Province,
			City:     user.City.String,
			Area:     user.Area.String,
			Type:     user.Type,
		})
	}
	resp = &types.QueryUserResponse{
		Count: count,
		List:  list,
	}
	return resp, nil
}
